﻿using _17bangMVC.Models;
using BLL.Entities;
using BLL.Repositories;
using SRV.ServiceInterface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GLB.Global;
using SRV.ViewModel.Email;
using System.Net.Mail;
using System.Net;

namespace SRV.ProdService
{
    public class UserService : BaseService,IUserService
    {
        private UserRepository userRepository;
        public UserService()
        {

            userRepository = new UserRepository(context);
        }

        public void GetEmail(ActivateModel model)
        {
            string code = model.Code;
            int userId = GetCurrentUser().Id;

            //准备Email
            MailMessage mail = new MailMessage
            {
                From = new MailAddress("hulu8930@163.com"),
                Subject = "激活Email",
                Body = $"感谢您的注册，您的注册码是{code}，点击<a href='/Email/Validate?uId={userId}&code={code}'>完成注册</a>",
                IsBodyHtml = true,
            };
            mail.To.Add(model.EmailAddress);
            //发送Email
            SmtpClient client = new SmtpClient
            {
                Host = "smtp.163.com",
                Port = 25,
                Credentials = new NetworkCredential("hulu8930", "PDODULRQIWXICTUF"),
                EnableSsl = false,
            };
            client.Send(mail);
        }

        public ActivateModel GetEmailCode(int uid)
        {
            User user = userRepository.Find(uid);
            return mapper.Map<ActivateModel>(user);
        }
            public void ValidEmail(int uid)
        {
            User user = userRepository.Find(uid);
            user.hasValid = true;
        }
        public ProfileModel GetProfile()
        {
            //User user = userRepository.Find(id);
            ProfileModel model = mapper.Map<ProfileModel>(GetCurrentUser().Profile);
            return model;
        }

        public string GetPwdById(int id)
        {
            User user = userRepository.Find(id);
            return user.Password;
        }

        public int Register(UserModel model)
        {
            User user = mapper.Map<User>(model);//UserModel映射给User
            user.Password = model.Password.MD5Encrypt();
            
            user.Register();
            int id = userRepository.Save(user);
            return user.Id;

        }
        public UserModel GetByName(string name)
        {
            User user = userRepository.GetByName(name);
            UserModel model = mapper.Map<UserModel>(user);
            return model;
        }



    }
}
